import { Request, Response } from 'express';
import { UserRole, RoleDisplayNames, RolePermissions } from '@/consts/role';
import { RoleManager } from '@/utils/roleUtils';
import User from '@/models/User';

// 获取所有可用角色
export const getAllRoles = async (req: Request, res: Response): Promise<void> => {
  try {
    const rolesInfo = RoleManager.getAllRolesInfo();
    
    res.json({
      success: true,
      message: '获取角色列表成功',
      data: {
        roles: rolesInfo,
        total: rolesInfo.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取角色列表失败',
      error: error instanceof Error ? error.message : 'Unknown error'
    });
  }
};

// 获取角色统计信息
export const getRoleStats = async (req: Request, res: Response): Promise<void> => {
  try {
    const users = User.findAll();
    const usersWithRoles = users.map(user => ({
      ...user,
      password: '' 
    }));
    const stats = RoleManager.getRoleStats(usersWithRoles);
    
    const statsWithDisplayNames = Object.entries(stats).map(([role, count]) => ({
      role: role as UserRole,
      displayName: RoleDisplayNames[role as UserRole],
      count,
      permissions: RolePermissions[role as UserRole]
    }));
    
    res.json({
      success: true,
      message: '获取角色统计成功',
      data: {
        statistics: statsWithDisplayNames,
        totalUsers: users.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取角色统计失败',
      error: error instanceof Error ? error.message : 'Unknown error'
    });
  }
};

// 根据角色获取用户列表
export const getUsersByRole = async (req: Request, res: Response): Promise<void> => {
  try {
    const { role } = req.params;

    if (!role) {
      res.status(400).json({
        success: false,
        message: '角色参数不能为空'
      });
      return;
    }

    // 验证角色
    const validation = RoleManager.validateRole(role);
    if (!validation.isValid) {
      res.status(400).json({
        success: false,
        message: validation.error
      });
      return;
    }

    const users = User.findAll();
    const usersWithRoles = users.map(user => ({
      ...user,
      role: user.role as UserRole,
      password: '' 
    }));
    const filteredUsers = RoleManager.filterUsersByRole(usersWithRoles, validation.role!);
    
    res.json({
      success: true,
      message: `获取${RoleDisplayNames[validation.role!]}用户列表成功`,
      data: {
        role: validation.role,
        displayName: RoleDisplayNames[validation.role!],
        users: filteredUsers,
        count: filteredUsers.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户列表失败',
      error: error instanceof Error ? error.message : 'Unknown error'
    });
  }
};

// 检查用户权限
export const checkUserPermission = async (req: Request, res: Response): Promise<void> => {
  try {
    const { userId } = req.params;
    const { permission } = req.query;

    if (!userId) {
      res.status(400).json({
        success: false,
        message: '用户ID不能为空'
      });
      return;
    }

    if (!permission || typeof permission !== 'string') {
      res.status(400).json({
        success: false,
        message: '请提供要检查的权限'
      });
      return;
    }

    const user = User.findById(userId);
    if (!user) {
      res.status(400).json({
        success: false,
        message: '用户不存在'
      });
      return;
    }

    const userWithRole = {
      ...user,
      role: user.role as UserRole,
      password: '' 
    };
    const hasPermission = RoleManager.userHasPermission(userWithRole, permission);
    
    res.json({
      success: true,
      message: '权限检查完成',
      data: {
        userId: user.id,
        username: user.username,
        role: user.role,
        roleDisplayName: RoleDisplayNames[user.role as UserRole],
        permission,
        hasPermission,
        allPermissions: RolePermissions[user.role as UserRole]
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '权限检查失败',
      error: error instanceof Error ? error.message : 'Unknown error'
    });
  }
};

// 角色比较
export const compareRoles = async (req: Request, res: Response): Promise<void> => {
  try {
    const { role1, role2 } = req.query;
    
    if (!role1 || !role2 || typeof role1 !== 'string' || typeof role2 !== 'string') {
      res.status(400).json({
        success: false,
        message: '请提供两个要比较的角色'
      });
      return;
    }
    
    const validation1 = RoleManager.validateRole(role1);
    const validation2 = RoleManager.validateRole(role2);
    
    if (!validation1.isValid) {
      res.status(400).json({
        success: false,
        message: `第一个角色无效: ${validation1.error}`
      });
      return;
    }
    
    if (!validation2.isValid) {
      res.status(400).json({
        success: false,
        message: `第二个角色无效: ${validation2.error}`
      });
      return;
    }
    
    const comparison = RoleManager.compareRoles(validation1.role!, validation2.role!);
    let result: string;
    
    if (comparison > 0) {
      result = `${RoleDisplayNames[validation1.role!]} 权限高于 ${RoleDisplayNames[validation2.role!]}`;
    } else if (comparison < 0) {
      result = `${RoleDisplayNames[validation2.role!]} 权限高于 ${RoleDisplayNames[validation1.role!]}`;
    } else {
      result = `${RoleDisplayNames[validation1.role!]} 与 ${RoleDisplayNames[validation2.role!]} 权限相等`;
    }
    
    res.json({
      success: true,
      message: '角色比较完成',
      data: {
        role1: {
          value: validation1.role,
          displayName: RoleDisplayNames[validation1.role!],
          permissions: RolePermissions[validation1.role!]
        },
        role2: {
          value: validation2.role,
          displayName: RoleDisplayNames[validation2.role!],
          permissions: RolePermissions[validation2.role!]
        },
        comparison,
        result
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '角色比较失败',
      error: error instanceof Error ? error.message : 'Unknown error'
    });
  }
};
